package org.jeecg.modules.bobo.cms.service.impl;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialCountResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNewsBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialVideoInfoResult;
import me.chanjar.weixin.mp.bean.material.WxMpNewsArticle;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.bobo.cms.entity.LbPortalPost;
import org.jeecg.modules.bobo.cms.mapper.LbPortalPostMapper;
import org.jeecg.modules.bobo.cms.service.ILbPortalPostService;
import org.jeecg.modules.bobo.common.service.ILbAutoServiceLogService;
import org.jeecg.modules.bobo.common.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 文章列表
 * @Author: jeecg-boot
 * @Date:   2020-12-22
 * @Version: V1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LbPortalPostServiceImpl extends ServiceImpl<LbPortalPostMapper, LbPortalPost> implements ILbPortalPostService {
    @Autowired
    private ILbAutoServiceLogService autoServiceLogService;
    @Autowired
    private WxMpService wxMpService;
    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;
    @Value(value = "${jeecg.bizPath}")
    private String bizPath;
    @Override
    public boolean importWeChatMedia() {
        try {
            //获取图文总数
//            WxMpMaterialCountResult wxMpMaterialCountResult = this.wxMpService.getMaterialService().materialCount();
            //计算最新图文区间
//            int offset = wxMpMaterialCountResult.getNewsCount()-10;
            //根据类别分页获取图文素材列表
            WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = this.wxMpService.getMaterialService().materialNewsBatchGet(0, 20);
            LbPortalPost lbPortalPost =null;
            List<LbPortalPost> lbPortalPosts =new ArrayList<>();
            if (wxMpMaterialNewsBatchGetResult.getItems().size()>0){
                for (WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem item : wxMpMaterialNewsBatchGetResult.getItems()){
                    try{
                        int index=0;
                        for (WxMpNewsArticle article:item.getContent().getArticles()){
                            lbPortalPost = new LbPortalPost();
                            String id = item.getMediaId() + "_" + index;
                            LbPortalPost byId = getById(id);
                            if (byId !=null){
                                lbPortalPost=byId;
                            }else{
                               lbPortalPost.setId(id);
                               lbPortalPost.setParentId("1");
                                lbPortalPost.setPostStatus("1");
                                lbPortalPost.setPostHits(0);
                                lbPortalPost.setCommentCount(0);
                                lbPortalPost.setPostFavorites(0);
                                lbPortalPost.setPostLike(0);
                            }
//                           if (StringUtils.isNotBlank(article.getThumbMediaId())){
//                               lbPortalPost.setThumbnail(downloadMaterial(article.getThumbMediaId()));
//                           }
                           if(StringUtils.isNotBlank(article.getThumbUrl())){
                               lbPortalPost.setThumbnail(downloadMaterialByUrl(article.getThumbUrl()));
                           }
                            if (item.getUpdateTime()!=null){
                                lbPortalPost.setPublishedTime(item.getUpdateTime());
                            }
                           lbPortalPost.setPostContent(article.getContent());
                           lbPortalPost.setPostTitle(article.getTitle());
                           lbPortalPost.setPostExcerpt(article.getDigest());
                           lbPortalPost.setPostSource(article.getUrl());
                            index++;
                            lbPortalPosts.add(lbPortalPost);
                        }

                    }catch (Exception e){
                        autoServiceLogService.setLog("文章自动插入错误", "", e.getMessage());
                        continue;
                    }
                }
            }
            saveOrUpdateBatch(lbPortalPosts);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            autoServiceLogService.setLog("微信获取素材列表错误", "", e.getMessage());
        }

        return false;
    }

    private String downloadMaterialByUrl(String thumbUrl) {
        String biz=bizPath + File.separator + DateUtil.getDate("yyyy-MM-dd")+ File.separator;
        File file = new File(uploadpath + File.separator + biz);
        if (!file.exists()) {
            file.mkdirs();// 创建文件根目录
        }
        String fileName =System.currentTimeMillis() + ".jpg";
        String savePath = file.getPath() + File.separator + fileName;

        //根据图片地址构建URL
        try {
        URL url= new URL(thumbUrl);
        URLConnection conn = url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(10000);
            conn.connect();
            try (InputStream inputStream = conn.getInputStream()) {
                FileUtils.copyInputStreamToFile(inputStream, new File(savePath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return biz+fileName;
    }

    public String downloadMaterial(String mediaId){
        String biz=bizPath + File.separator + DateUtil.getDate("yyyy-MM-dd")+ File.separator;
        File file = new File(uploadpath + File.separator + biz);
        if (!file.exists()) {
            file.mkdirs();// 创建文件根目录
        }
       String fileName =mediaId+"_"+ System.currentTimeMillis() + ".jpg";
        String savePath = file.getPath() + File.separator + fileName;
        try (InputStream inputStream = this.wxMpService.getMaterialService()
                    .materialImageOrVoiceDownload(mediaId)) {
            FileUtils.copyInputStreamToFile(inputStream, new File(savePath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        return biz+fileName;
    }
}
